/*
 * librolgps, part of the RolGPS Proyect
 *
 *   
 * Copyright (C) Pablo Alejandro Costesich <rhfixer@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package deployers.sqlite;

import java.util.Vector;

/**
 *
 * @author xeph
 */
public class Table {

    private Vector<Field> fields = new Vector();
    private String name = "";
    private boolean isEmpty = true;
    private boolean trimName=false;

    public Table(String tableName) {
        if(trimName==true) tableName.trim();
        this.name = tableName;
    }

    public void addField(Field field) {
        fields.add(field);
        isEmpty = false;
    }
    
    public void addField(Field... fields) {
        for(Field field: fields){
            this.fields.add(field);
        }
        isEmpty = false;
    }

    public void deleteField(Field field) throws Exception {
        if (isEmpty == true && !fields.isEmpty()) {
            throw new Exception();
        } else {
            int index = fields.indexOf(field.getName());
            if (index < 0) {
                throw new Exception();
            } else {
                fields.removeElementAt(index);
            }
        }

    }

    protected String sql() throws Exception {
        String sql = null;
        if (isEmpty == true) {
            throw new Exception();
        } else {
            sql = "CREATE TABLE IF NOT EXISTS \'" + name + "\' (";
            String temporalFields="";
            for (Field field : fields) {
                temporalFields += ", " + field.getName() + " " + field.getTypesAsString();
            }
            sql += temporalFields.substring(1);
            sql += ");";
        }
        return sql;
    }
}
